using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using PHSRAG.WebControls;
using Utils = PHSRAG.Insight21.InsightUtilities;

namespace PHSRAG.Insight21.COI
{
    /// <summary>
    /// This page allows the user(super-user) to search and add users to the hierarchy.
    /// </summary>
    public partial class AddCoIUsers : BasePage
    {
        #region Constants

        /// <summary>Unique string(key) to identify or cache the page index </summary>
        private const string AddCOIUserPageIndexKey = "AddCOIUserPageIndexKey_17993E66-4AE1-4a72-9380-A7A79C63941E";

        /// <summary>annunciator's general message</summary>
        private const string AnnunciatorTitle = "The following error(s) occurred...";

        /// <summary>Index column in the database</summary>
        private const string PersonIdField = "PersonId";

        #endregion

        #region Instance Variables (Protected)

        /// <summary>Provides navigation withing the application </summary>
        /// <summary>provides information about the current page and the link to the parent page</summary>
        /// <summary>This section(panel)will be hidded if the requested as a popup</summary>
        /// <summary>Expansion toggler to show hide the advanced search panel</summary>
        /// <summary>Identifies that whether or not the post back is valid<summary>
        /// <summary>Provides details about the execution</summary>
        /// <summary>Control that sets the focus on page load</summary>
        /// <summary>The Control that indicates the persisting execution at the background </summary>
        /// <summary>Grid that displays the search results matching the entered criteria</summary>
        /// <summary>Control that facilitates datagrid paging at the bottom of the grid </summary>
        /// <summary>Grid that displays the selected users results.</summary>
        /// <summary>web control of type button that takes the user to the referer page.</summary>
        /// <summary>Html table that holds the controls in the expansion toggler control </summary>
        /// <summary>Control that facilitates datagrid paging at the bottom of the grid </summary>
        /// <summary>Web control of type button to add the selected users from serach results grid to selected results grid </summary>
        /// <summary>Web control of type button that adds the selected list of user in Selected results grid to hierarchy</summary>
        /// <summary>provides navigation within the COI module</summary>
        /// <summary>The section which hides or unhides the datagrid and pager controls from search results grid(depending on the record count)</summary>
        /// <summary>The section which hides or unhides the datagrid and pager controls for selected users grid(depending on the record count)</summary>
        /// <summary>web control of type button that triggers the save action in the database</summary>
        //Toggler control
        protected ExpansionToggler expansionToggler;

        #endregion

        #region Instance Variables (Private)

        //cachePolicy
        private ICachePolicy applicationCachePolicy;
        private ICachePolicy cachePolicy;
        private string keyField = "Id";
        //Displays the search criteria with labels
        //Page cache policy
        private ICachePolicy pageCachePolicy;
        //Application cache
        //Referring page identifier
        private int referingPage = 2;
        //Id column(Datkey column) for the data source

        #endregion

        #region property variables

        //parent Id to add users
        private int personId;

        #endregion

        #region Private Properties

        /// <summary> 
        /// Get the COIUserSummary object relevant to the passed in search criteria.
        /// </summary>
        private COIUserSummary COIUserSummary
        {
            get
            {
                COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                if (cOIUserSummary == null)
                {
                    cOIUserSummary = new COIUserSummary(cachePolicy);
                }
                if ((searchContext != null))
                {
                    cOIUserSummary.Load(DataAccess.ConnectionString, searchCriteria, GetPersonId(), referingPage);
                    cOIUserSummary.Cache();
                }

                return cOIUserSummary;
            }
        }

        /// <summary>
        /// Gets/Sets the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AddCOIUsersPageKey) as Hashtable;
                return (h == null || h[AddCOIUserPageIndexKey] == null) ? 0 : (int) h[AddCOIUserPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AddCOIUsersPageKey) as Hashtable;
                if (h == null)
                {
                    h = new Hashtable();
                }
                h[AddCOIUserPageIndexKey] = value;
                searchResults.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.AddCOIUsersPageKey, h);
            }
        }

        /// <summary>
        /// Gets the Cached COIUserSummary object
        /// </summary>
        private COIUserSummary GetCOIUserSummaryFromCache
        {
            get { return cachePolicy.GetCachedObject(COIUserSummary.CacheKey) as COIUserSummary; }
        }

        /// <summary>
        /// Gets/Sets the person Id for whom the selected users will be added.
        /// </summary>
        private int GetPersonId()
        {
            try
            {
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                    if (incomingPageHash.ContainsKey(Keys.ImpersonationIdKey))
                    {
                        personId = Convert.ToInt32(incomingPageHash[Keys.ImpersonationIdKey]);
                    }
                }
                else
                {
                    personId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
                }
            }
            catch (Exception ex)
            {
                ExceptionReport.WriteToEventLog("Error occurred while trying to get the parent Id(AddCOIUsers.GetPersonIds())", ex, true, ExceptionReport.ReportType.Error);
                annunciator.Message = "Error occurred while trying to get the parent Id";
            }
            return personId;
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Retrieves the CommonSearchContext from the cache and
        /// performs a User search through the system.
        /// </summary>
        private void PerformSearch()
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            if (searchContext != null)
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
        }

        /// <summary>
        /// Loads the COIUser details only for those to displayed on the page.
        /// </summary>
        private void LoadDataGrid()
        {
            try
            {
                COIUserSummary cOIUserSummary = COIUserSummary;
                if (cOIUserSummary != null)
                {
                    searchResults.VirtualItemCount = bottomPager.RecordCount =
                        topPager.RecordCount = cOIUserSummary.Count;
                    int currentPageIndex = CurrentPageIndex;
                    int pageCount = (topPager.RecordCount/searchResults.PageSize) +
                        (((topPager.RecordCount%searchResults.PageSize) == 0) ? 0 : 1);
                    bottomPager.PageCount = topPager.PageCount = pageCount;
                    bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

                    DataTable table = cOIUserSummary.GetSummaryList(
                        currentPageIndex*searchResults.PageSize, searchResults.PageSize, DataAccess.ConnectionString, referingPage);
                    searchResults.DataSource = table;
                    searchResults.DataKeyField = keyField;
                    searchResults.DataBind();

                    if (table.Rows.Count == 0)
                    {
                        gridContainer.Visible = false;
                        addtoList.Visible = false;
                        annunciator.Message = "The search criteria yielded no results.";
                    }
                    else
                    {
                        gridContainer.Visible = true;
                        addtoList.Visible = true;
                        annunciator.Message = string.Empty;
                        ManagePagination();
                        ManageNavigationLinks();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionReport.WriteToEventLog("Error occurred while trying to load the search results(Error occured at AddCOIUser.LoadDataGrid())", ex, true, ExceptionReport.ReportType.Error);
                annunciator.Message = "Error occurred while trying to load the search results";
            }
        }

        /// <summary>
        /// Initilize the first record, last record and current page values for the pager controls.
        /// Set the current page index to 0 and manage navigation links.
        /// </summary>
        private void InitializePager()
        {
            bottomPager.FirstRecord = topPager.FirstRecord = 1;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(searchResults.PageSize, searchResults.Items.Count);
            bottomPager.CurrentPage = topPager.CurrentPage = 1;
            CurrentPageIndex = 0;
            ManageNavigationLinks();
        }

        /// <summary>
        /// Enables or Disables links to other pages within the grid
        /// </summary>
        private void ManageNavigationLinks()
        {
            bottomPager.EnableFirstPage = topPager.EnableFirstPage =
                bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                    (searchResults.CurrentPageIndex != 0);

            bottomPager.EnableLastPage = topPager.EnableLastPage =
                bottomPager.EnableNextPage = topPager.EnableNextPage =
                    (searchResults.CurrentPageIndex != (topPager.PageCount - 1));
        }

        /// <summary>
        /// Pagination management
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            searchResults.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*searchResults.PageSize;
            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            int lastRecord = COIUserSummary.Count;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + searchResults.PageSize, lastRecord);
        }


        /// <summary>
        /// Uncaches all objects with data for this page.
        /// </summary>
        private void PurgeCache()
        {
            System.Diagnostics.Trace.WriteLine("Purging Supervisor Summary...");
            COIUserSummary coiUserSummary = GetCOIUserSummaryFromCache;
            if (coiUserSummary != null)
            {
                coiUserSummary.Purge();
                cachePolicy.UnCache(COIUserSummary.CacheKey);
            }
        }

        /// <summary>
        /// This methos will open the AddExternals page as popup.
        /// </summary>
        private void OpenAddExternalPage()
        {
            StringBuilder script = new StringBuilder();
            script.Append("\n<script language=JavaScript id='externalUsersPage'>\n");
            script.Append("var editorWin = null; \n");
            CacheOutGoingData(true);
            script.Append("editorWin = window.open('AddExternal.aspx', 'externalUsersPage', 'width=1000, height=600, status=yes, toolbar=no, scrollbars=yes, resizable=yes'); \n");
            script.Append("</script>");
            if (!ClientScript.IsClientScriptBlockRegistered("externalUsersPage"))
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "externalUsersPage", script.ToString());
            }
        }

        /// <summary>
        /// Caches outgoing data with incoming data key for use across pages.
        /// </summary>
        /// <param name="showTargetAsPopUp">set to true, if the target page is to be shown as a popup</param>
        private void CacheOutGoingData(bool showTargetAsPopUp)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ShowAsPopUp, showTargetAsPopUp);
            outgoingData.Add(Keys.ImpersonationIdKey, GetPersonId());
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
        }

        /// <summary>
        /// This method will perform redirection back to the referring page after clearing the search criteria.
        /// </summary>
        private void RedirectToReferrer()
        {
            PurgeCache();
            CacheOutGoingData(false);
            ClearSearchCriteria();
            Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.HierarchyMaintenanceURL", ""), false);
        }

        /// <summary>
        /// Clears the selection criteria 
        /// </summary>
        private void ClearSearchCriteria()
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

            if (searchContext != null)
            {
                searchContext.Reset(Page.Request.Url.ToString());
            }
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion

        # region Event handlers

        /// <summary>
        /// The page load event handler
        /// </summary>
        /// <param name="sender">Sender,that raised the event</param>
        /// <param name="e">argiments related to the sender</param>	
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;
                breadCrumb.Add("Add COI Users", Settings.GetKeyValue("SubNavigation.CoI.AddUsersURL", string.Empty), Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

                if (!IsPostBack && postbackGuard.IsValid)
                {
                    searchResults.PageSize = selectedUsers.PageSize = Settings.GetKeyValue("COIDataGrid.ItemsPerPage", 20);
                    CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

                    gridContainer.Visible = false;
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                coiSubNavigation.SelectedLink = "Hierarchy Maintenance";
                coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
            }
        }

        /// <summary>
        /// Handles events raised by sorting the datagrid.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache ?? new COIUserSummary(cachePolicy);

                    cOIUserSummary.SortColumn = e.SortExpression;
                    cOIUserSummary.SortAscending = (cOIUserSummary.SortColumn == e.SortExpression) ? !cOIUserSummary.SortAscending : cOIUserSummary.SortAscending;
                    cOIUserSummary.Cache();
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// This event is raised when the page index property is changed on the pager control.
        /// The page's DataGrid is reloaded with the data belonging to page specified by the index.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            try
            {
                searchResults.CurrentPageIndex = e.NewPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the FirstPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the first page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the LastPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the last page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                int lastPageIndex = topPager.PageCount - 1;
                CurrentPageIndex = lastPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the NextPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the next page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the PreviousPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the previous page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for event raised while each data grid item is created.
        /// If the item being created is the data grid header, do the following:
        /// Add the appropriate sort symbol to denote ascending/descending sequence for the current sort column.
        /// This requires us to locate the cell which corresponding to the column within the collection of TableCell
        /// maintained by the DataGridItem which is under creation. That collection is indexed numerically, the value being
        /// the position of the column within the columns collection maintained by the data grid.
        /// One simple way to do this is to create static mapping between the name of the column and its index. However, this
        /// suffers from the shortcoming that if the sequence of columns is changed on the page, the static binding MUST
        /// be changed too. If they get out of sync, we would be sorting on inappropriate columns!
        /// To avoid this, and to render the code independent of how the page gets managed, we will build a Hashtable of
        /// column indeces, keyed by the sort expression of each column. That way, we could do a quick lookup to get the
        /// index of a column and set the sort symbol on that column.
        /// If the item being created is a data row item, disable its view state.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                    Label sortSymbol = new Label();
                    sortSymbol.Text = (cOIUserSummary.SortAscending) ? InsightUtilities.Constants.SortAscendingText : InsightUtilities.Constants.SortDescendingText;
                    sortSymbol.Font.Name = InsightUtilities.Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in searchResults.Columns)
                    {
                        columnMap[column.SortExpression] = searchResults.Columns.IndexOf(column);
                    }

                    string sortColumn = cOIUserSummary.SortColumn;
                    if (columnMap.ContainsKey(sortColumn))
                    {
                        e.Item.Cells[(int) columnMap[sortColumn]].Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header breadcrumb navigates.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
                coiSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Purges the cache before the COI subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnSubNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event handler for the "AddToList" button click.
        /// Note:Adds the selected users in the search results grid to the selected user grid.
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnAddToList(object sender, ImageClickEventArgs e)
        {
            try
            {
                COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                DataTable selectedUserTable;
                /* Determine which rows in the grid have been selected, and move them into the 
				 * Selections DataTable */
                if (postbackGuard.IsValid && cOIUserSummary != null)
                {
                    foreach (DataGridItem dgi in searchResults.Items)
                    {
                        CheckBox chkBox = (CheckBox) dgi.Cells[4].Controls[1];
                        if (chkBox != null && chkBox.Checked)
                        {
                            cOIUserSummary.AddSelectedUserToList((int) searchResults.DataKeys[dgi.ItemIndex]);
                        }
                    }
                    cOIUserSummary.Cache();
                    selectedUserTable = cOIUserSummary.GetSelectedUsersSummary(DataAccess.ConnectionString);
                    if (selectedUserTable.Rows.Count > 0)
                    {
                        selectedUsers.DataSource = selectedUserTable;
                        selectedUsers.DataKeyField = keyField;
                        selectedUsers.DataBind();
                        selectedUsersContainer.Visible = true;
                        save.Visible = true;
                    }
                    else
                    {
                        selectedUsersContainer.Visible = false;
                        save.Visible = false;
                    }
                    PerformSearch();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event handler to add the selected users to the hierarchy
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnSave(object sender, ImageClickEventArgs e)
        {
            try
            {
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                   
                    int parentId = Convert.ToInt32(incomingPageHash[Keys.ImpersonationIdKey]);
                    int hierarchyTypeId = (null == incomingPageHash[Keys.HierarchyTypeIdKey] || (int)COIUser.HierarchyType.None == Convert.ToInt32(incomingPageHash[Keys.HierarchyTypeIdKey])) ? (int)COIUser.HierarchyType.Institutional : Convert.ToInt32(incomingPageHash[Keys.HierarchyTypeIdKey]);
                    if (selectedUsers.Visible)
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add("parentId");
                        dt.Columns.Add("childId");
                        dt.Columns.Add("removed");
                        dt.Columns.Add("HierarchyTypeId");

                        foreach (DataGridItem dgi in selectedUsers.Items)
                        {
                            CheckBox chkBox = (CheckBox) dgi.Cells[4].Controls[1];
                            if (chkBox != null && chkBox.Checked)
                            {
                                DataRow dr = dt.NewRow();
                                dr["parentId"] = parentId;
                                dr["childId"] = (int) selectedUsers.DataKeys[dgi.ItemIndex];
                                dr["removed"] = 0;
                                dr["HierarchyTypeId"] = hierarchyTypeId;
                                dt.Rows.Add(dr);
                            }
                        }
                        if (dt.Rows.Count > 0)
                        {
                            DataSet ds = new DataSet();
                            ds.Tables.Add(dt);
                            COIUserSummary.AddUserHierarchyMap(DataAccess.ConnectionString, ds);
                            RedirectToReferrer();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        

        /// <summary>
        /// Even handler for the Cancel button click
        /// Action performed: Redirect back to the referrer page without adding the selected users to the hierarchy.
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnCancel(object sender, ImageClickEventArgs e)
        {
            try
            {
                RedirectToReferrer();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event handler for Add Users button click(Opens the AddExternals page)
        /// </summary>
        /// <param name="sender">Sender,that raised the event</param>
        /// <param name="e">arguments related to the sender</param>	
        private void OnAddExternal(object sender, ImageClickEventArgs e)
        {
            try
            {
                OpenAddExternalPage();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Search event handler

        /// <summary>
        /// Handler for the event raised by the CommonSearch control when the "Clear Selection" buttion is clicked upon.
        /// The control clears the criteria (specific to this module).
        /// Since in the page life-cycle, the Load occurs before the Clear event, we have to instigate a re-load of the
        /// data grid to refelect the fact that the search criteria has been cleared.
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnClearSelection(object sender, CommandEventArgs e)
        {
            try
            {
                gridContainer.Visible = false;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Initiates the search by calling PerformSearch
        /// </summary>
        /// <param name="args">Argument associated with the event (contains the search criteria dictionary)</param>
        protected void OnSearch(SearchCriteriaArgs args)
        {
            try
            {
                PerformSearch();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            applicationCachePolicy = (Policy.ICachePolicy) Application[Policy.Names.ApplicationCachePolicyKey];

            coiSubNavigation.Navigate += new CommandEventHandler(OnSubNavigate);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.topPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.topPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.topPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.topPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.searchResults.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            this.searchResults.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.OnPageIndexChanged);
            this.searchResults.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.bottomPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.bottomPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.bottomPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.bottomPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.addtoList.Click += new ImageClickEventHandler(OnAddToList);
            this.cancel.Click += new ImageClickEventHandler(OnCancel);
            this.addExternals.Click += new ImageClickEventHandler(OnAddExternal);
            this.save.Click += new ImageClickEventHandler(OnSave);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}